<template>
  <div id="assignPermissionPage">
    <!-- 使用麵包屑組件 -->
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />
    <!-- 角色簡要信息面板 -->
    <a-space direction="vertical" style="width: 100%">
      <a-card title="角色信息" :loading="loading">
        <a-descriptions :column="2">
          <a-descriptions-item label="角色ID">{{
            roleDetail.id
          }}</a-descriptions-item>
          <a-descriptions-item label="角色名稱">{{
            roleDetail.name
          }}</a-descriptions-item>
        </a-descriptions>
      </a-card>
      <a-card title="已分配的權限" :loading="permissionsLoading">
        <a-collapse v-model:activeKey="activeKey" style="width: 100%">
          <a-collapse-panel
            v-for="(module, index) in permissionList"
            :key="index.toString()"
            :header="module.module"
          >
            <!-- 添加調試信息 -->
            <div v-if="module.permissions.length === 0">該模塊暫無權限</div>
            <a-flex wrap="wrap" gap="large" v-else>
              <a-tag color="#2F54EB" v-for="permission in module.permissions">
                {{ permission.title }}
              </a-tag>
            </a-flex>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
      <a-card title="已分配的菜單" :loading="menusLoading">
        <!-- 確保 treeData 有數據後再渲染 a-tree -->
        <a-tree
          v-if="treeData.length > 0"
          defaultExpandAll
          :tree-data="treeData"
          :field-names="fieldNames"
          :show-line="true"
        >
        </a-tree>
        <div v-else>暫無菜單分配</div>
      </a-card>
    </a-space>
    <BackButton />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { roleApi } from "@/api";
import { useRoute } from "vue-router";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import BackButton from "@/components/BackButton.vue";
import { usePermissionStore } from "@/store/permissionStore";
import { useMenuStore } from "@/store/menuStore";
import { TreeProps } from "ant-design-vue/es/vc-tree";

// 定義 Permission 和 PermissionModule 類型
interface Permission {
  name: string;
  title: string;
}

interface PermissionModule {
  module: string;
  permissions: Permission[];
}

const route = useRoute();
const roleDetail = ref({ id: 0, name: "" }); // 角色詳情數據
const activeKey = ref<string[]>([]);
const breadcrumbItems = [
  { url: "/role", name: "角色管理" },
  { url: "", name: "詳情" },
];

const permissionStore = usePermissionStore();
const permissionList = ref<PermissionModule[]>([]);

const assignedPermissionKeys = ref<string[]>([]); // 存儲所有已分配的權限name
const assignedMenuKeys = ref<string[]>([]); // 存儲所有已分配的菜單ID

const menuStore = useMenuStore();
interface MenuItem {
  id: string;
  title: string;
  children?: MenuItem[];
}

const treeData = ref<TreeProps["treeData"] & MenuItem[]>(menuStore.menuTree);

const fieldNames: TreeProps["fieldNames"] = {
  key: "id",
  // title: 'title',
};

onMounted(async () => {
  const roleId = Number(route.params.id);
  fetchRoleDetail(roleId);
  if (permissionStore.groupedPermissionList.length === 0) {
    await permissionStore.fetchGroupedPermissionList();
  }
  await fetchAssignedPermissions(roleId);
  // 整理權限數據
  const filterPermissions = (
    permissions: any,
    assignedPermissionKeysSet: any
  ) => {
    return permissions.filter((permission: any) =>
      assignedPermissionKeysSet.has(permission.name)
    );
  };

  const assignedPermissionKeysSet = new Set(assignedPermissionKeys.value);
  permissionList.value = permissionStore.groupedPermissionList.map((module) => {
    return {
      ...module,
      permissions: filterPermissions(
        module.permissions,
        assignedPermissionKeysSet
      ),
    };
  });

  // 生成摺疊面板包含所有 key 的數組，用於控制展開狀態
  activeKey.value = permissionList.value.map((_, index) => index.toString());

  if (menuStore.menuTree.length === 0) {
    await menuStore.fetchMenuTree();
    treeData.value = menuStore.menuTree;
  }
  await fetchAssignedMenus(roleId);
  const assignedMenuKeysSet = new Set(assignedMenuKeys.value);
  treeData.value = menuStore.menuTree
    .map((menu) => {
      return {
        ...menu,
        children: menu.children?.filter((child: any) =>
          assignedMenuKeysSet.has(child.id)
        ),
      };
    })
    .filter((menu) => {
      // 若 children 存在且不為空，或者沒有 children 屬性，則保留該菜單
      return menu.children?.length > 0 || !menu.children;
    });
});

const loading = ref(true);
const fetchRoleDetail = async (roleId: number) => {
  loading.value = true;
  try {
    const { data } = await roleApi.getRoleDetail(roleId);
    roleDetail.value = data;
  } catch (error) {
    console.error("獲取角色詳情失敗", error);
  } finally {
    loading.value = false;
  }
};

const permissionsLoading = ref(false);
const fetchAssignedPermissions = async (roleId: number) => {
  permissionsLoading.value = true;
  try {
    const { data } = await roleApi.getRolePermissions(roleId);
    assignedPermissionKeys.value = data;
  } catch (error) {
    console.error("獲取已分配權限失敗", error);
  } finally {
    permissionsLoading.value = false;
  }
};

const menusLoading = ref(false);
const fetchAssignedMenus = async (roleId: number) => {
  menusLoading.value = true;
  try {
    const { data } = await roleApi.getRoleMenuIds(roleId);
    assignedMenuKeys.value = data;
  } catch (error) {
    console.error("獲取已分配菜單失敗", error);
  } finally {
    menusLoading.value = false;
  }
};

//整理菜單數據
</script>

<style scoped></style>
